package com.mmall.concurrency;

import com.mmall.concurrency.annotations.NotThreadSafe;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.concurrent.*;

@Slf4j
@NotThreadSafe
public class ConcurrencyTest {

    private static int count = 0;

    // 请求用户总数
    private static int clientTotal = 5000;

    // 同一时刻执行的线程数
    private static int threadTotal = 200;
    //执行的主方法
    public  static void main(String[] args) throws Exception{

        // 模拟并发执行
        // 线程池
        ExecutorService executorService = Executors.newCachedThreadPool();
        //  信号量
        final Semaphore semaphore = new Semaphore(threadTotal);
        // 计数器闭锁
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);

        //放入请求到线程池
        for (int i = 0;i < clientTotal;i++){
            executorService.execute( () ->{
                // 引入信号量
                try {
                    // 判断当前线程允许被执行？ -- 能返回值 -- 执行下面
                    semaphore.acquire();
                    add();
                    // 释放进程
                    semaphore.release();
                }catch (Exception e){
                    log.error("【信号量】"+e.getMessage());
                }

                // 引入闭锁
                countDownLatch.countDown();
            });
            countDownLatch.await();
            executorService.shutdown();
        }
    }

    // 计数方法
    private static void add(){
        count++;
    }
}
